package me.fanwu.services.alipay.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.google.common.collect.ImmutableMap;
import me.fanwu.services.alipay.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/*
 * Wupher 编写于 2016/11/3.
 */
@Service
public class PaymentServiceImpl implements PaymentService{
    private AlipayClient alipayClient;

    @Autowired
    public PaymentServiceImpl(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }

    @Override
    public String pay(String orderID,String authCode, String subject, String storeID,
                      Float paymentAmount, String token) {


        Map<String, Object> bizContents1= ImmutableMap.of(
                "out_trade_no", orderID,
                "scene", "bar_code",
                "auth_code", authCode,
                "subject", subject,
                "store_id", storeID);
        Map<String, Object> bizContents2 = ImmutableMap.of("total_amount", paymentAmount, "timeout_express", "2m");

        Map<String, Object> params = new HashMap<>(bizContents1);
        params.putAll(bizContents2);
        String json = JSON.toJSONString(params);
        AlipayTradePayRequest payRequest = new AlipayTradePayRequest();
        payRequest.setBizContent(json);
        AlipayTradePayResponse response;
        try {
             response = alipayClient.execute(payRequest,token);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
        return response.getTradeNo();
    }
}
